/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package interfaz;

import clases.ClsContraladorEventos;
import clases.ClsDatabase;
import clases.ClsMetodos;
import java.awt.Image;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author ser
 */
public class dlgPartidaCopiar extends javax.swing.JDialog {

    private ClsDatabase bd = new ClsDatabase();
    DefaultComboBoxModel modelCboUnidad = new DefaultComboBoxModel();
    ClsContraladorEventos controlEvent = new ClsContraladorEventos();
    private ClsMetodos metodos = new ClsMetodos();
    String array_arbol[][] = new String[80][3];

    public dlgPartidaCopiar(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public dlgPartidaCopiar(java.awt.Frame parent, boolean modal, String codigo, String descripcion) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        Image image = new ImageIcon(getClass().getResource("/resource/icon/principales/Logo.png")).getImage();

        //Para poner Icon en un JDialog
        ((java.awt.Frame) this.getOwner()).setIconImage(image);
        jTextField1.setText(codigo);
        jTextField2.setText(descripcion);

        metodos.arbol_llenar(tree, "idnivel, nombre, nivel FROM partida_nivel", "WHERE estado='A' order by idnivel asc ;", array_arbol);
        jTextField2.requestFocus();
        iconos_arbol();
    }

    public String getNodeIndex(JTree tree, TreeNode node) {
        TreeNode root = (TreeNode) tree.getModel().getRoot();
        if (node == root) {
            return "";
        }
        TreeNode parent = node.getParent();
        if (parent == null) {
            return null;
        }
        String parentIndex = getNodeIndex(tree, parent);
        if (parentIndex == null) {
            return null;
        }
        return parentIndex + "." + parent.getIndex(node);
    }

    public void iconos_arbol() {
        DefaultTreeCellRenderer render = (DefaultTreeCellRenderer) tree.getCellRenderer();
        render.setLeafIcon(new ImageIcon(getClass().getResource("/resource/icon/principales/peque/tre_folder.png")));
        render.setOpenIcon(new ImageIcon(getClass().getResource("/resource/icon/principales/peque/tre_folder.png")));
        render.setClosedIcon(new ImageIcon(getClass().getResource("/resource/icon/principales/peque/tre_folder.png")));
    }

    public String arbol_id_buscar(String valor) {
        String v = "";
        for (int i = 0; i < array_arbol.length; i++) {
            if (array_arbol[i][2] != null) {
//                System.out.println(array_arbol[i][2]);
                if (array_arbol[i][2].equals(valor)) {
                    v = array_arbol[i][0];
                    //break;
                }
            }
        }
        return v;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        btnCopiar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        tree = new javax.swing.JTree();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Copiar partidas");

        jPanel1.setBackground(new java.awt.Color(225, 235, 247));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Codigo:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 210, 50, 20));

        jTextField1.setEditable(false);
        jPanel1.add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 210, 60, -1));

        jTextField2.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        jPanel1.add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 210, 350, -1));

        btnCopiar.setText("Copiar");
        btnCopiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCopiarActionPerformed(evt);
            }
        });
        jPanel1.add(btnCopiar, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 250, 90, -1));

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        jPanel1.add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 250, 90, -1));

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Partidas");
        javax.swing.tree.DefaultMutableTreeNode treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("Basicos");
        treeNode2.add(treeNode3);
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("Construcción");
        treeNode2.add(treeNode3);
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("Saneamiento");
        javax.swing.tree.DefaultMutableTreeNode treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("captación");
        treeNode3.add(treeNode4);
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("sergio");
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("miguel");
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        tree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        tree.setFocusable(false);
        tree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                treeMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                treeMousePressed(evt);
            }
        });
        tree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                treeValueChanged(evt);
            }
        });
        jScrollPane4.setViewportView(tree);

        jPanel1.add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 470, 170));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 470, 290));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 498, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void treeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeMouseClicked
        //        DefaultMutableTreeNode nseleccionado = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
        //        JOptionPane.showMessageDialog(this, nseleccionado.getPath());
    }//GEN-LAST:event_treeMouseClicked

    private void treeMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeMousePressed
    }//GEN-LAST:event_treeMousePressed

    private void treeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_treeValueChanged
    }//GEN-LAST:event_treeValueChanged

    private void btnCopiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCopiarActionPerformed
        int v = tree.getLeadSelectionRow();
        if (v != -1) {
            if (tree.getLeadSelectionPath().getPathCount() == 4) {
                TreePath currentSelection = tree.getSelectionPath();
                if (currentSelection != null) {
                    DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection.getLastPathComponent());

                    String codigo;
                    codigo = metodos.generarCodigollaves("select substring(idpartida,3,4) from partida_base ", 4);
                    codigo = "H_" + codigo;
                    bd.transaccion_libre("insert into partida_base SELECT '" + codigo + "', '" + jTextField2.getText().replace("'", "") + "', rendimiento, precio, tipo, idpartida_generica, idunidad, uso, estado, '" + arbol_id_buscar(getNodeIndex(tree, currentNode).trim()) + "' FROM partida_base where idpartida='" + jTextField1.getText() + "';");
                    bd.transaccion_libre("insert into partida_base_detalle  SELECT '" + codigo + "', idinsumo, cuadrilla, cantidad, precio_unitario, precio_parcial FROM partida_base_detalle where idpartida='" + jTextField1.getText() + "';");
                    this.dispose();
                }
            } else {
                javax.swing.JOptionPane.showMessageDialog(this, "Seleccione el grupo especifico" );
            }
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione el grupo especifico" );
        }
    }//GEN-LAST:event_btnCopiarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgPartidaCopiar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgPartidaCopiar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgPartidaCopiar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgPartidaCopiar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlgPartidaCopiar dialog = new dlgPartidaCopiar(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnCopiar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTree tree;
    // End of variables declaration//GEN-END:variables
}
